//
//  Extension.swift
//  LPStretchableHeaderView
//
//  Created by Tony on 2017/8/24.
//  Copyright © 2017年 Tony. All rights reserved.
//

import UIKit

// 屏幕宽度
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
// 屏幕高度
let SCREEN_WIDTH = UIScreen.main.bounds.size.width
//标题字的属性
let naviBarTitleAttributes = NSDictionary(object: UIColor.white, forKey: NSAttributedStringKey.foregroundColor as NSCopying)
let RETURNBUTTONTITLEMARGIN = "  "

extension UIView {
    
    public var x: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            var frame = self.frame
            frame.origin.x = newValue
            self.frame = frame
        }
    }
    
    public var y: CGFloat{
        get {
            return self.frame.origin.y
        }
        set {
            var frame = self.frame
            frame.origin.y = newValue
            self.frame = frame
        }
    }
    
    /** 宽 */
    public var width: CGFloat{
        get {
            return self.frame.size.width
        }
        set {
            var frame = self.frame
            frame.size.width = newValue
            self.frame = frame
        }
    }
    
    /** 高 */
    public var height: CGFloat{
        get {
            return self.frame.size.height
        }
        set {
            var frame = self.frame
            frame.size.height = newValue
            self.frame = frame
        }
    }
    
    /** 下 */
    public var bottom: CGFloat{
        get {
            return self.frame.origin.y + self.frame.size.height
        }
        
        set {
            var frame = self.frame
            frame.origin.y = newValue - self.frame.size.height
            self.frame = frame
        }
    }
    
    /** 右 */
    public var right: CGFloat{
        get {
            return self.frame.origin.x + self.frame.size.width
        }
        
        set {
            var frame = self.frame
            frame.origin.x = newValue - self.frame.size.width
            self.frame = frame
        }
    }
    
    /** 尺寸 */
    public var size: CGSize{
        get {
            return self.frame.size
        }
        
        set {
            var frame = self.frame
            frame.size = newValue
            self.frame = frame
        }
    }
    
    /** 竖直中心对齐 */
    public var centerX: CGFloat{
        get {
            return self.center.x
        }
        
        set {
            var center = self.center
            center.x = newValue
            self.center = center
        }
    }
    
    /** 水平中心对齐 */
    public var centerY: CGFloat{
        get {
            return self.center.y
        }
        
        set {
            var center = self.center
            center.y = newValue
            self.center = center
        }
    }
}
extension UILabel {
    convenience init (x:CGFloat,y:CGFloat,height:CGFloat,text:String,font:CGFloat,aliment:NSTextAlignment,color:UIColor) {
        let labelFont = UIFont.boldSystemFont(ofSize: font)
        let width = Utils.adjustLabelWidth(text: text, font: labelFont, height: height)
        self.init(frame: CGRect(x: x, y: y, width: width, height: height))
        self.text = text
        self.font = labelFont
        self.textAlignment = aliment
        self.textColor = color
    }
    convenience init (x:CGFloat,y:CGFloat,height:CGFloat,text:String,font:CGFloat,aliment:NSTextAlignment,textColor:UIColor,backgroundColor:UIColor) {
        self.init(x: x, y: y, height: height, text: text, font: font, aliment: aliment, color: textColor)
        self.backgroundColor = backgroundColor
    }
    class func width(title:String, font:UIFont) -> CGFloat{
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 1000, height: 0))
        label.text = title
        label.font = font
        label.sizeToFit()
        return label.frame.size.width
    }
}
extension CGRect {
    init (center:CGPoint,size:CGSize) {
        let sizeWidth = size.width
        let sizeHeight = size.height
        let centerX = center.x
        let centerY = center.y
        let startPointX = centerX - sizeWidth/2
        let startPointY = centerY - sizeHeight/2
        self.init(origin:CGPoint(x:startPointX,y:startPointY),size:size)
    }
}
extension UIImage {
    class func image(_ image:UIImage,alpha:CGFloat) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0)
        let ctx = UIGraphicsGetCurrentContext()
        let area = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
        ctx?.scaleBy(x: 1, y: -1)
        ctx?.translateBy(x: 0, y: -area.size.height)
        ctx?.setBlendMode(.multiply)
        ctx?.setAlpha(alpha)
        ctx?.draw(image.cgImage!, in: area)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    class func image(color:UIColor) -> UIImage{
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}
extension UIButton {
     func setBackgroundImage(_ image: UIImage?,alpha:CGFloat, for state: UIControlState){
        let newImage = UIImage.image(image!, alpha: alpha)
        self.setBackgroundImage(newImage, for: state)
    }

    func setBackgroundColor(_ backgroundColor:UIColor, for state: UIControlState){
        let image = UIImage.image(color: backgroundColor)
        self.setBackgroundImage(image, for: state)
    }
    func setBackgroundAlpha(_ alpha:CGFloat, for state: UIControlState){
        let color = self.backgroundColor!
        let newColor = UIColor(color:color, alpha: alpha)
        self.setBackgroundColor(newColor, for: state)
    }
    func setBackgroundColor(_ color:UIColor,alpha:CGFloat, for state: UIControlState){
        let newColor = UIColor(color:color, alpha: alpha)
        self.setBackgroundColor(newColor, for: state)
    }
}
extension UINavigationBar {
    func setBackgroundColor(_ backgroundColor:UIColor){
        let image = UIImage.image(color: backgroundColor)
        self.setBackgroundImage(image, for: UIBarMetrics.default)
    }
}


extension UIColor {
    
    class var Main: UIColor {
        return UIColor(red: 74 / 255.0, green: 163 / 255.0, blue: 243 / 255.0, alpha: 1.0)
    }
    
    class var Gray: UIColor {
        return UIColor(red: 242 / 255.0, green: 243 / 255.0, blue: 248 / 255.0, alpha: 1.0)
    }
    class var APP: UIColor {
        return UIColor(red: 240 / 255.0, green: 104 / 255.0, blue: 52 / 255.0, alpha: 1.0)
    }
    class var APPDisabled: UIColor {
        return UIColor(red: 240 / 255.0, green: 104 / 255.0, blue: 52 / 255.0, alpha: 0.5)
    }
    class var Drop: UIColor {
        return Utils.kRGBColorFromHex(rgbValue: 0x3BB083)
    }
    class var LabelFont: UIColor {
        return Utils.kRGBColorFromHex(rgbValue: 0x333333)
    }
    class var LabelFontPlaceHolder: UIColor {
        return Utils.kRGBColorFromHex(rgbValue: 0x666666)
    }
    class var LevelLabelBackground: UIColor {
        return Utils.kRGBColorFromHex(rgbValue: 0xCE9533)
    }
    class var ThinLine: UIColor {
         return UIColor(red: 180 / 255.0, green: 180 / 255.0, blue: 180 / 255.0, alpha: 1.0)
    }
    class var Background: UIColor {
        return UIColor(red: 240 / 255.0, green: 240 / 255.0, blue: 240 / 255.0, alpha: 1.0)
    }
    class func RGB_COLOR(_ r:CGFloat, g:CGFloat, b:CGFloat, alpha:CGFloat) -> UIColor {
        return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
    }
    convenience init(color:UIColor,alpha:CGFloat) {
        let newColor = color.cgColor.copy(alpha: alpha)
        self.init(cgColor: newColor!)
    }
}
    public extension UIColor {
        
        convenience init(red: Int, green: Int, blue: Int, al: CGFloat) {
            assert(red >= 0 && red <= 255, "Invalid red component")
            assert(green >= 0 && green <= 255, "Invalid green component")
            assert(blue >= 0 && blue <= 255, "Invalid blue component")
            
            self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: al)
        }
        
        /// - Parameters:
        ///   - netHex: 16进制
        ///   - alpha: 透明度
        convenience init(netHex:Int, alpha: CGFloat) {
            self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff, al: alpha)
        }
        
        public convenience init(rgba: String) {
            var red: CGFloat   = 0.0
            var green: CGFloat = 0.0
            var blue: CGFloat  = 0.0
            var alpha: CGFloat = 1.0
            
            if rgba.hasPrefix("#") {
                var hexStr = (rgba as NSString).substring(from: 1) as NSString
                if hexStr.length == 8 {
                    let alphaHexStr = hexStr.substring(from: 6)
                    hexStr = hexStr.substring(to: 6) as NSString
                    
                    var alphaHexValue: UInt32 = 0
                    let alphaScanner = Scanner(string: alphaHexStr)
                    if alphaScanner.scanHexInt32(&alphaHexValue) {
                        let alphaHex = Int(alphaHexValue)
                        alpha = CGFloat(alphaHex & 0x000000FF) / 255.0
                    } else {
                        //SMJPrint("scan alphaHex error")
                    }
                }
                
                let rgbScanner = Scanner(string: hexStr as String)
                var hexValue: UInt32 = 0
                if rgbScanner.scanHexInt32(&hexValue) {
                    if hexStr.length == 6 {
                        let hex = Int(hexValue)
                        red   = CGFloat((hex & 0xFF0000) >> 16) / 255.0
                        green = CGFloat((hex & 0x00FF00) >> 8)  / 255.0
                        blue  = CGFloat(hex & 0x0000FF) / 255.0
                    } else {
                        print("invalid rgb string, length should be 6")
                    }
                } else {
                    //SMJPrint("scan hex error")
                }
            } else {
                print("invalid rgb string, missing '#' as prefix")
            }
            self.init(red:red, green:green, blue:blue, alpha:alpha)
        }
    }
    
    extension CGFloat {
        
        /// 输出格式化的String
        ///
        /// - Parameter format: eg: ".2" 保留两位小数
        /// - Returns: Formated String
        func toStringWithFormat(_ format: String) -> String {
            return String(format: "%\(format)f", self)
        }
        
        /// "###,##0.00"
        /// "0.00"
        /// 科学计数
        func toStringWithFormat1(_ format:String) -> String! {
            let nsnumberformaer = NumberFormatter()
            nsnumberformaer.positiveFormat = format
            nsnumberformaer.locale = Locale.current
            let BB = nsnumberformaer.string(from: NSNumber(value: Float(self)))!
            
            return BB
        }
        
        
        /// 输出为百分数
        ///
        /// - Returns: 以%结尾的 百分数输出
        func toPercentFormat() -> String {
            return String(format: "%.2f", self) + "%"
        }
    }
    
    extension String {
        
        func toDate(_ format:String) -> Date? {
            let dateformatter = DateFormatter()
            dateformatter.timeZone=TimeZone.autoupdatingCurrent
            dateformatter.dateFormat = format
            
            return dateformatter.date(from: self)
        }
    }
    
    extension Date {
        
        func toString(_ format:String) -> String {
            let dateformatter = DateFormatter()
            dateformatter.timeZone = TimeZone.autoupdatingCurrent
            dateformatter.dateFormat = format
            return dateformatter.string(from: self)
        }
        
        static func toDate(_ dateString: String, format: String) -> Date {
            let dateformatter = DateFormatter()
            //dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            dateformatter.dateFormat = format
            dateformatter.locale = Locale(identifier: "en_US")
            let date = dateformatter.date(from: dateString) ?? Date()
            return date
        }
    }
    
    
    extension Double {
        
        /// %.2f 不带科学计数
        func toStringWithFormat(_ format:String) -> String! {
            return NSString(format: format as NSString, self) as String
        }
        
        /// "###,##0.00"
        /// "0.00"
        /// 科学计数
        func toStringWithFormat1(_ format:String) -> String! {
            let nsnumberformaer = NumberFormatter()
            nsnumberformaer.positiveFormat = format
            nsnumberformaer.locale = Locale.current
            let BB = nsnumberformaer.string(from: NSNumber(value: self))!
            
            return BB
        }
    }


